package org.example.leetCode;

import java.util.Arrays;

/**
 * @author Administrator
 */
public class BuildTree {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        int length = preorder.length;
        if (length == 0) {
            return null;
        }

        //根节点
        int root = preorder[0];
        int index = 0;
        for (int i = 0; i < inorder.length; i++) {
            if (inorder[i] == root) {
                index = i;
                break;
            }
        }

        TreeNode treeNode = new TreeNode(root);
        treeNode.left = buildTree(Arrays.copyOfRange(preorder, 1, index + 1), Arrays.copyOfRange(inorder, 0, index));
        treeNode.right = buildTree(Arrays.copyOfRange(preorder, index + 1, length), Arrays.copyOfRange(inorder, index + 1, length));
        return treeNode;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }
}
